package storage;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;


public class DateTree {
	public HashMap<Integer,ArrayList<Integer>> dateList;
	
	public DateTree(int[] days, int[] times){
		dateList = new HashMap<Integer, ArrayList<Integer>>();
		dateList.put(0, new ArrayList<Integer>());
		dateList.put(1, new ArrayList<Integer>());
		dateList.put(2, new ArrayList<Integer>());
		dateList.put(3, new ArrayList<Integer>());
		dateList.put(4, new ArrayList<Integer>());
		dateList.put(5, new ArrayList<Integer>());
		dateList.put(6, new ArrayList<Integer>());
		
		for(int i=0;i<days.length;i++){
			for(int z =0;z<times.length;z++){
				dateList.get(days[i]).add(times[z]);
			}
		}
	}
	public Calendar getClosestDate(Calendar c){
		//We have to check a max of 7 times
		for(int i=0;i<7;i++){
			int day = i+(c.get(Calendar.DAY_OF_WEEK)-1);
			if(!dateList.get(day%7).isEmpty()){
				ArrayList<Integer> timeList = dateList.get(day%7);
				for(int z=0;z<timeList.size();z++){
					if(i!=0 ||timeList.get(z)+1>c.get(Calendar.HOUR_OF_DAY)){
						Calendar current = (Calendar)c.clone();
						current.add(Calendar.DAY_OF_WEEK, i);
						current.set(Calendar.HOUR_OF_DAY, (timeList.get(z)+1));
						current.set(Calendar.MINUTE,0);
						current.set(Calendar.SECOND,0);
						current.set(Calendar.MILLISECOND,0);
						return current;
					}
				}
			}
		}
		//If we've reached this point, the time in question is on the same day but has already
		//passed
		if(!dateList.get(c.get(Calendar.DAY_OF_WEEK)-1).isEmpty()){
			ArrayList<Integer> timeList = dateList.get(c.get(Calendar.DAY_OF_WEEK)-1);
			if(!timeList.isEmpty()){
				Calendar current = (Calendar)c.clone();
				current.add(Calendar.DAY_OF_WEEK, 7);
				current.set(Calendar.HOUR_OF_DAY, timeList.get(0)+1);
				current.set(Calendar.MINUTE,0);
				current.set(Calendar.SECOND,0);
				current.set(Calendar.MILLISECOND,0);
				return current;
			}
		}
		return null;
	}
}
